import { NextRequest, NextResponse } from 'next/server';
import { VideoService } from '@/app/lib/DataBase/database';
import path from 'path';
import { spawn } from 'child_process';

// 模拟获取当前用户ID的函数（实际项目中应该从认证系统获取）
const getCurrentUserId = (request: NextRequest): string | undefined => {
  // 在实际项目中，这里应该从JWT token或session中获取用户ID
  // 这里为了演示，我们使用一个固定值或从查询参数中获取
  const userIdParam = request.nextUrl.searchParams.get('userId');
  return userIdParam || undefined;
};

const runPy = (url: string, id: string): Promise<string> => {
  return new Promise((resolve, reject) => {
    const py = spawn('python', [path.join(process.cwd(), '../python', 'cover.py'), url, id]);
    let out = '', err = '';

    py.stdout.on('data', (d) => out += d);
    py.stderr.on('data', (e) => err += e);
    py.on('close', (code) => {
      if (code) reject(new Error(err));
      else resolve(out.trim());
    });
  });
}

// 根据ID获取视频
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  try {
    // 获取当前用户ID（实际项目中应该从认证系统获取）
    const userId = getCurrentUserId(request);

    // 使用新方法获取视频信息，包含用户评分和收藏状态
    const videoData = await VideoService.getVideoWithUserInfo(id, userId);
    if (!videoData) {
      return NextResponse.json({
        success: false,
        message: '视频不存在'
      }, { status: 404 });
    }

    // 判断是否存在封面
    if (!videoData.coverUrl) {
      // 执行Python脚本生成封面
      const result = await runPy(videoData.sourceUrl, id);
      if (result) {
        videoData.coverUrl = result;
        await VideoService.updateVideo(id, { coverUrl: result });
      }
    }

    return NextResponse.json({
      success: true,
      data: videoData
    });
  } catch (error) {
    console.error('获取视频失败:', error);
    return NextResponse.json({
      success: false,
      message: '获取视频失败',
      error: error instanceof Error ? error.message : '未知错误'
    }, { status: 500 });
  }
}

// 模拟检查用户是否为管理员的函数
const isAdminUser = (request: NextRequest): boolean => {
  // 在实际项目中，这里应该从认证系统或JWT token中获取用户角色信息
  // 这里简单地从查询参数中获取用户ID并假设ID为1的是管理员
  const userIdParam = request.nextUrl.searchParams.get('userId');
  return userIdParam === '1';
};

// 更新视频
export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params
  try {
    // 验证管理员权限
    if (!isAdminUser(request)) {
      return NextResponse.json({
        success: false,
        message: '您没有权限编辑视频',
      }, { status: 403 });
    }
    
    const {
      title,
      coverUrl,
      durationSeconds,
      category,
      description,
      sourceUrl,
      publishedAt,
    } = await request.json();
    const updateData = {
      title,
      cover_url: coverUrl,
      duration_seconds: durationSeconds,
      category,
      description,
      source_url: sourceUrl,
      published_at: publishedAt,
    }
    const result = await VideoService.updateVideo(id, updateData);

    return NextResponse.json({
      success: true,
      data: result,
      message: '视频更新成功'
    });
  } catch (error) {
    console.error('更新视频失败:', error);
    return NextResponse.json({
      success: false,
      message: '更新视频失败',
      error: error instanceof Error ? error.message : '未知错误'
    }, { status: 500 });
  }
}

// 处理评分和收藏操作
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const userId = getCurrentUserId(request);

    if (!userId) {
      return NextResponse.json({
        success: false,
        message: '用户未登录，无法操作'
      }, { status: 401 });
    }

    const body = await request.json();
    const { id } = await params

    // 根据请求体中的操作类型区分是评分还是收藏
    if (typeof body.rating === 'number') {
      // 评分操作
      const { rating } = body;

      // 验证评分
      if (rating < 1 || rating > 5) {
        return NextResponse.json({
          success: false,
          message: '评分必须是1-5之间的数字'
        }, { status: 400 });
      }

      // 执行评分
      const result = await VideoService.rateVideo(userId, id, rating);

      return NextResponse.json({
        success: true,
        data: result,
        message: '评分成功'
      });
    } else if (typeof body.isFavorite === 'boolean') {
      // 收藏操作
      const { isFavorite } = body;

      // 执行收藏操作
      const result = await VideoService.toggleFavorite(userId, id, isFavorite);

      return NextResponse.json({
        success: true,
        data: result,
        message: isFavorite ? '收藏成功' : '取消收藏成功'
      });
    } else {
      return NextResponse.json({
        success: false,
        message: '无效的请求：缺少rating或isFavorite参数'
      }, { status: 400 });
    }
  } catch (error) {
    console.error('操作失败:', error);
    return NextResponse.json({
      success: false,
      message: '操作失败',
      error: error instanceof Error ? error.message : '未知错误'
    }, { status: 500 });
  }
}

// 删除视频
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params
  try {
    const result = await VideoService.deleteVideo(id);

    return NextResponse.json({
      success: true,
      data: result,
      message: '视频删除成功'
    });
  } catch (error) {
    console.error('删除视频失败:', error);
    return NextResponse.json({
      success: false,
      message: '删除视频失败',
      error: error instanceof Error ? error.message : '未知错误'
    }, { status: 500 });
  }
}
